#include "de_jpeg.h"



//判断文件是否是jpeg文件
int is_jpeg_file(char *filename,struct jpeg_file *pfd)
{
	int ret;
	uint32_t word;

    pfd->cinfo.err = jpeg_std_error(&pfd->jerr);
	//创建一个jpeg_compress_struct结构体
    jpeg_create_decompress(&pfd->cinfo);
	
	//指定jpeg解压的源文件
    jpeg_stdio_src(&pfd->cinfo, pfd->fp);
	
	//解析jpeg文件，解析完成后可获得图像的格式
    ret = jpeg_read_header(&pfd->cinfo, TRUE);
	if(ret < 0){
		printf("file is not jpg ...\n");
		return -1;
	}

	return JPEG_FILE;
}


void free_jpeg(struct jpeg_file *jf)
{
	free(jf->buffer);
}



int decode_jpeg(char *filename,struct jpeg_file *jf)
{
	int ret;
	uint32_t word;
	unsigned char *buf_cpy;
	//临时变量行buffer
	uint8_t *pucbuffer;
	
	//放大倍率
	jf->cinfo.scale_num = 1;//2
	//缩小倍率
	jf->cinfo.scale_denom = 1;

	//jf->cinfo.out_color_space = JCS_RGB;

	//对cinfo所指定的源文件进行解压，并将解压后的数据存到cinfo结构体的成员变量中。
    jpeg_start_decompress(&jf->cinfo);
	//获取图片基本信息
    jf->row_size = jf->cinfo.output_width * jf->cinfo.output_components;
    jf->width = jf->cinfo.output_width;
    jf->height = jf->cinfo.output_height;
	jf->Bpp = jf->cinfo.output_components;
    jf->size = jf->row_size * jf->cinfo.output_height;
	
	//分配内存空间 
	pucbuffer = malloc(jf->row_size);
    jf->buffer = malloc(jf->size);

#if 0

	log_i("jpeg_color_space=%d\n",jf->cinfo.jpeg_color_space);

    printf("size: %d w: %d h: %d row_size: %d ,Bpp: %d\n",
			jf->size,jf->width,jf->height,jf->row_size,jf->Bpp);
#endif
			
	//缓冲指针指向buffer		
	buf_cpy = jf->buffer;

    while (jf->cinfo.output_scanline < jf->cinfo.output_height){
        //可以读取RGB数据到buffer中，参数3能指定读取多少行
		jpeg_read_scanlines(&jf->cinfo, &pucbuffer, 1);
        //复制到内存
		memcpy(buf_cpy , pucbuffer, jf->row_size);
		buf_cpy = buf_cpy + jf->row_size;
    }

	// 完成解码
	jpeg_finish_decompress(&jf->cinfo);
	free(pucbuffer);
	//释放结构体
    jpeg_destroy_decompress(&jf->cinfo);

	return 0;
}




